//
//  AppDelegate.swift
//  ydy_weibo
//
//  Created by 杨德勇 on 16/7/11.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        let account = UserAccount.loadAccount()
        print("视图加载的时候是否存在account",account)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        //注册通知
        registerNortification()
        
        setThemeColor()
        
        
        window?.rootViewController = defaultRootController()

        
        return true
    }
    
    //MARK:-
    //MARK:设置通知
    private func registerNortification(){
        //添加监听的时候，object的意思是监听哪个对象发出的，nil指监听所有对象
        NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(AppDelegate.switchToRootVc(_:)), name: AppSwitchRootViewControler, object: nil)
    }

    @objc private func switchToRootVc(n:NSNotification){
        if (n.object as? String) != nil {
            window?.rootViewController = WelcomeViewController()
            return
        }
        
        window?.rootViewController = MainViewController()
    }
    //取消监听
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK:-
    //MARK:设置主题颜色

    func setThemeColor(){
        UINavigationBar.appearance().tintColor = themecolor
        UITabBar.appearance().tintColor = themecolor
    }
    
    //判断用户是否已经登陆，判断用户软件版本是否最新
    private func defaultRootController() -> UIViewController {
        if UserAccountViewModel().userLogin {
            
            return isNewVersion() ? NewFeatureViewController():WelcomeViewController()
            
        }
        
        return MainViewController()
    }
    
    //判断是不是最新版本
    private func isNewVersion() -> (Bool){
        
        //取得当前版本
        let versionString = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionString)
        
        //获取旧版本
        let versionKey = "versionKey"
        
        let userDefault = NSUserDefaults.standardUserDefaults()
        let lastversion = userDefault.doubleForKey(versionKey)
        
        userDefault.setDouble(versionNum!, forKey: versionKey)
        
        userDefault.synchronize()
        
        
        return versionNum > lastversion
    }
    
}

